package Utility;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Random;

import Messages.Message;
import Messages.MessageType;

public class ClientUtilities {
	public static final HashMap<Integer, Host> serversMap = new HashMap<Integer, Host>();
	static {
		try {
			FileReader fr = new FileReader("ServerConfiguration");
			BufferedReader br = new BufferedReader(fr);
			String line;
			int serverCount = 0;
			while ((line = br.readLine()) != null) {
				String[] lineContent = line.split(":");
				String[] hostNameAndPort = lineContent[1].split("#");
				Host carryHostNameAndPort = new Host();
				carryHostNameAndPort.setHostName(hostNameAndPort[0]);
				carryHostNameAndPort.setPortNumber(hostNameAndPort[1]);
				serversMap.put(serverCount, carryHostNameAndPort);
				serverCount++;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public Host pickRandomServerToConnect(int totalNumberOfNumbers) {
		Random generateRandomNumber = new Random();
		int randomNumber = generateRandomNumber.nextInt(totalNumberOfNumbers);
		return serversMap.get(randomNumber);
	}

	public int pickRandomLockToRequestFromClient(int totalNumberofLocks) {
		Random generateRandomNumber = new Random();
		int randomNumber = generateRandomNumber.nextInt(totalNumberofLocks);
		return randomNumber;
	}
	
	
	public static LinkedList<Host> getAllHostExcludingMe(int excludeHost){
		LinkedList<Host> hostLinkedList = new LinkedList<Host>();
		for (Entry<Integer, Host> e : serversMap.entrySet()) {
			if (e.getKey() != excludeHost) {
				hostLinkedList.add(e.getValue());
			}
		}
		return hostLinkedList;

	}
	public static Message getMessage(MessageType message,int proposal,int lockValue){
		Message m = new Message();		
		m.setMessageType(message);
		m.setProposalNumber(proposal);
		m.setLockValue(lockValue);
		return m;
		}
	
	public static String getMessageSeparator(){
		return "******************************************************************************";
	}
	
}
